package org.mch.func.img.cut;

import java.awt.Rectangle;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;

import javax.imageio.ImageIO;
import javax.imageio.ImageReadParam;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;

public class OperateImage {

	public void cutImageTest(File src, File dest) throws IOException {
		if(!src.getPath().endsWith(".jpg")){
			return;
		}
		BufferedImage bufSrcImg = ImageIO.read(new FileInputStream(src));
		int srcImgWidth = bufSrcImg.getWidth();
		int srcImgHeight = bufSrcImg.getHeight();

		int newImgWidth = srcImgWidth;
		int newImgHeight = srcImgHeight - 24;

		Iterator<ImageReader> iterator = ImageIO.getImageReadersByFormatName("jpg");
		ImageReader reader = iterator.next();
		InputStream in = new FileInputStream(src);

		ImageInputStream iis = ImageIO.createImageInputStream(in);

		reader.setInput(iis, true);

		ImageReadParam param = reader.getDefaultReadParam();
		Rectangle rect = new Rectangle(0, 0, newImgWidth, newImgHeight - 24);
		param.setSourceRegion(rect);
		BufferedImage bi = reader.read(0, param);
		ImageIO.write(bi, "jpg", dest);

		iis.close();
		in.close();

	}

	public synchronized static void cutImage(String src, String dest, int x, int y, int w, int h) throws IOException {
		BufferedImage bufSrcImg = ImageIO.read(new FileInputStream(src));
		int srcImgWidth = bufSrcImg.getWidth();
		int srcImgHeight = bufSrcImg.getHeight();

		int newImgWidth = srcImgWidth;
		int newImgHeight = srcImgHeight - 24;

		Iterator<ImageReader> iterator = ImageIO.getImageReadersByFormatName("jpg");
		ImageReader reader = iterator.next();
		InputStream in = new FileInputStream(src);

		ImageInputStream iis = ImageIO.createImageInputStream(in);

		reader.setInput(iis, true);

		ImageReadParam param = reader.getDefaultReadParam();
		Rectangle rect = new Rectangle(x, y, newImgWidth, newImgHeight - 24);
		param.setSourceRegion(rect);
		BufferedImage bi = reader.read(0, param);
		ImageIO.write(bi, "jpg", new File(dest));

		iis.close();
		in.close();

	}
}
